<template>
  <div>
    <el-form
      :model="updaterole"
      ref="roleForm"
      label-width="100px"
      label-position="right"
      style="width: 400px"
      :rules="rules"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="updaterole.name"
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-tree
      :data="authList"
      show-checkbox
      node-key="index"
      :default-expand-all="true"
      :default-checked-keys="checkedKeys"
      @check-change="handleCheckChange"
      ref="tree"
    >
    </el-tree>
  </div>
</template>

<script>
    import menuList from '@/config/menuConfig';
export default {
  data() {
    return {
      updaterole: {
        
      },
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      authList:[],
      checkedKeys:[],
    };
  },
  props: ['role'],
  mounted (){
    console.log("role",this.role); 
    this.updaterole = {...this.role} 
    this.authList = this.gettAuthNodes(menuList)
    this.checkedKeys = this.role.menus
  },
  watch: {
    role(val){
        if(val){
            this.$nextTick(()=>{
                this.updaterole={...val}
                this.checkedKeys=val.menus
                this.$refs["tree"].setCheckedKeys(this.checkedKeys)
            })
        }
    }
  },
  components: {},
  methods: {
    getMenus(){
        this.updaterole.menus = this.checkedKeys
        return this.updaterole
    },
    handleCheckChange(data, checked, indeterminate) {
        if(checked){
            this.checkedKeys.push(data.index)
        }else{
            if(this.checkedKeys.indexOf(data.index) !== -1){
                this.checkedKeys.splice(this.checkedKeys.indexOf(data.index),1)
            }           
        }
      },
    gettAuthNodes(menusList){
        return menusList.map(item=>{
            if(!item.children){
                return{
                    index:item.index,
                    label:item.title
                }
            }else{
                return{
                    index:item.index,
                    label:item.title,
                    children:this.gettAuthNodes(item.children)
                }
            }
        })
    }
  },
};
</script>

<style scoped>
</style>